import React, {useEffect, useState} from 'react';
import stylse from './index.module.less'

const Index: React.FC<{ data: number | string, type: 'yellow' | 'blue', showValue?: boolean, className?: string }> =
    ({
         data,
         type,
         showValue = true,
         className = ''
     }) => {
        const [percent, setPercent] = useState('0%')

        useEffect(() => {
            if (data) {
                if (typeof data === 'string') {
                    if (data.endsWith('%')) {
                        setPercent(data + '')
                    } else {
                        setPercent(Number(data) > 1 ? '100%' : Math.round(Number(data) * 10000) / 100 + '%')
                    }
                } else {
                    setPercent(data > 1 ? '100%' : Math.round(data * 10000) / 100 + '%')
                }
            } else {
                setPercent('0%');
            }
        }, [data])

        return (
            <div className={`${stylse['bar-horizontal']} ${className}`}>
                <div className={stylse[`bar-horizontal--${type}`]} style={{width: percent}}></div>
                {showValue && <span>{percent}</span>}
            </div>
        );
    };

export default Index;